package cn.codesea.housework_user.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickWorkerListener;
import cn.codesea.housework_user.adapter.RYTJListRcvAdapter;
import cn.codesea.housework_user.entity.Order;
import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.entity.Worker;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.OrderService;
import cn.codesea.housework_user.net.service.WorkerService;
import cn.codesea.housework_user.utils.SPUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 人员推荐页.最终下单界面
 */
public class RYTJListActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    RYTJListRcvAdapter adapter;
    List<Worker> workers = new ArrayList<>();
    private LinearLayoutManager mLinearLayoutManager;

    @BindView(R.id.search_iv)
    ImageView search_iv;
    @BindView(R.id.search_et)
    EditText search_et;

    @BindView(R.id.confirm_tv)
    TextView confirm_tv;

    Order order;

    Worker worker;

    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rytjlist);
        ButterKnife.bind(this);
        init();
    }

    private void init(){
        initData();
        initView();
    }

    private void initData() {
        user = SPUtil.getUser(RYTJListActivity.this);

        order = (Order) getIntent().getSerializableExtra("order");

        WorkerService service = ServiceGenerator.createService(WorkerService.class);
        Call<Result> call = service.workerRecommend(order.getServiceid());
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();

                if ( result.getRes() == null){
                    return;
                }

                Type type = new TypeToken<List<Worker>>(){}.getType();
                workers.clear();
                workers.addAll((List<Worker>)new Gson().fromJson(String.valueOf(result.getRes()),type));
                adapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {
                Toast.makeText(RYTJListActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void initView(){

        // 初始化 toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new RYTJListRcvAdapter(this,workers);
        adapter.setRecyclerItemClickListener(new OnRecyclerItemClickWorkerListener() {
            @Override
            public void onItemClick(int Position, List<Worker> list) {

            }
        });
        mLinearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(adapter);

    }

    @OnClick(R.id.search_iv)
    public void search_iv(){

    }

    @OnClick(R.id.confirm_tv)
    public void confirm_tv(){

        for (Worker worker :workers){
            if (worker.isChecked()){
                order.setWorkerid(worker.getWorkerid());
                order.setStatus(1);// 已接单状态
                break;
            }
        }

        if (!SPUtil.isLogin(RYTJListActivity.this)){
            Dialog dialog = new AlertDialog.Builder(RYTJListActivity.this)
                    .setTitle("提示")
                    .setMessage("您处于未登录状态，请先登录！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(RYTJListActivity.this,LoginActivity.class));
                        }
                    })
                    .setNegativeButton("取消",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
            return;
        }

        // 判断子女、老人
        if (0 == user.getType()){// 子女

            startActivity(new Intent(RYTJListActivity.this,JHListActivity.class).putExtra("order",order).putExtra("userid",user.getUserid()));

        }else if (1 == user.getType()){// 老人
            order.setOlderid(user.getUserid());
            OrderService service = ServiceGenerator.createService(OrderService.class);
            Call<Result> call = service.order(order);
            call.enqueue(new Callback<Result>(){
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body());
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(RYTJListActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result){
        if (result.getState() == 200){

            Dialog dialog = new AlertDialog.Builder(RYTJListActivity.this)
                    .setTitle("提示")
                    .setMessage( "下单成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(RYTJListActivity.this,MainActivity.class));
                            finish();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();

        }else {
            Toast.makeText(RYTJListActivity.this,"下单错误！",Toast.LENGTH_SHORT).show();
        }
    }
}
